import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_demo_k/view/custom_app_bar.dart';

class StreamBuilderTest extends StatefulWidget {
  static const String routeName = '/stream_builder';

  const StreamBuilderTest({super.key});

  @override
  State<StreamBuilderTest> createState() => _StreamBuilderTestState();
}

class _StreamBuilderTestState extends State<StreamBuilderTest> {
  final Stream<int> _stream = (() {
    final controller = StreamController<int>();
    int counter = 0;
    Timer.periodic(const Duration(seconds: 1), (timer) {
      controller.add(counter++);
      if (counter > 10) {
        timer.cancel();
        controller.close();
      }
    });
    return controller.stream;
  })();

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        title: 'StreamBuilder',
      ),
      body: Center(
        child: StreamBuilder<int>(
          stream: _stream,
          builder: (context, snapshot) {
            ///它会开始监听提供的流。它会建立一个监听器来接收流中的事件。
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const CircularProgressIndicator();
            }
            ///流出错
            else if (snapshot.hasError) {
              return Text('Error: ${snapshot.error}');
            } else if (snapshot.connectionState == ConnectionState.active ||
                snapshot.connectionState == ConnectionState.done) {
              return Text('Counter: ${snapshot.data}');
            }
            return Container();
          },
        ),
      ),
    );
  }
}
